package club.hicode.daydayup.sslFile.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.*;
import java.nio.channels.FileChannel;
import java.util.Date;

@ChannelHandler.Sharable
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    private boolean first = true;
    private FileOutputStream fos;
    private BufferedOutputStream bufferedOutputStream;
    private Long length = 0L;

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        first = true;
        System.out.println(ctx.channel().localAddress().toString() + " channelActive"+'-'+ System.currentTimeMillis());
    }

    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress().toString() + " channelInactive"+'-'+ System.currentTimeMillis());
        System.out.println("lengthAll:"+length);
        // close stream
        if(bufferedOutputStream!=null){
        	bufferedOutputStream.flush();
            bufferedOutputStream.close();
        }
        first = false;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        // create File
        if (first) {
            System.out.println("create File");
            first = false;
            File file = new File("/Volumes/Repository/Others/2.mp4");
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                fos = new FileOutputStream(file);
                bufferedOutputStream = new BufferedOutputStream(fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            return;
        }

		FileChannel channel = fos.getChannel();
		// write file
        ByteBuf buf = (ByteBuf) msg;

        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        length += bytes.length;
        try {
            bufferedOutputStream.write(bytes, 0, bytes.length);
            buf.release();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
        //System.out.println(length);
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        ctx.close();
       // System.out.println("异常信息：\r\n" + cause.getMessage());
        cause.printStackTrace();
    }

}